package com.market.product.controller;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.market.category.dao.CategoryDao;
import com.market.category.domain.CategoryCommand;
import com.market.product.dao.ProductDao;
import com.market.product.domain.ProductCommand;
import com.market.util.ProPagingUtil;

@Controller
public class ProListController {
	private int pageSize = 10;
	private int blockCount = 10;
	
	@Autowired
	private ProductDao productDao;
	@Autowired
	private CategoryDao categoryDao;
	
	@ModelAttribute("categoryItem")
	public List<CategoryCommand> initMarket(){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("keyWord", "all");		
		List<CategoryCommand> list = categoryDao.list(map);		
		return list;
	}

	@RequestMapping("/productList.do")
	public ModelAndView form(@RequestParam(value="pageNum",defaultValue="1")int currentPage,
							 //@RequestParam(value="keyField",defaultValue="")String keyField,
							 @RequestParam(value="searchMarket",defaultValue="all")String keyWord,
							 @RequestParam(value="searchCategory",defaultValue="all")String keyWord2){
		String pagingHtml = "";
		/*
		if(log.isDebugEnabled()){
			log.debug("currentPage : " + currentPage);
			log.debug("keyField : " + keyField);
			log.debug("keyWord : " + keyWord);
		}*/
		
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("keyWord", keyWord);
		map.put("keyWord2", keyWord2);
		
		int count = productDao.getRowCount(map);		
		
		ProPagingUtil page = new ProPagingUtil(keyWord, keyWord2,
				currentPage, count, pageSize, blockCount, "productList.do");
		
		pagingHtml = page.getPagingHtml().toString();//???
		
		map.put("start", page.getStartCount());
		map.put("end", page.getEndCount());
	
		List<ProductCommand> list = null;
	
		if(count > 0){
			list = productDao.list(map);
		}else{
			list = Collections.emptyList();
		}
		
		int number = count-(currentPage-1)*pageSize;//총 전시될 페이지?
		
		ModelAndView mav = new ModelAndView();
		mav.setViewName("productList");
		mav.addObject("count", count);//총글 수
		mav.addObject("list", list);//전시될 목록
		mav.addObject("pagingHtml", pagingHtml);//페이지 목록
		mav.addObject("number", number);
		mav.addObject("pageNum",currentPage);
		mav.addObject("searchMarket", keyWord);
		mav.addObject("searchCategory", keyWord2);
		return mav;
	}
}
